const express = require('express')
const cors = require('cors')
const { connectDB, initDB } = require('./config/db.js')
const userRoutes = require('./routes/user.js')
const chatRoutes = require('./routes/chat.js')
const dotenv = require('dotenv')
const { verifyEmailConfig } = require('./config/email.js')

dotenv.config()

const app = express()
const PORT = process.env.PORT || 3000

// CORS 配置
app.use(cors({
  origin: ['http://localhost:5173', 'app://.*'],
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}))

// 中间件
app.use(express.json())

// 处理未捕获的异常
process.on('uncaughtException', (err) => {
  console.error('未捕获的异常:', err)
  process.exit(1)
})

process.on('unhandledRejection', (err) => {
  console.error('未处理的Promise拒绝:', err)
  process.exit(1)
})

// 初始化应用
const initApp = async () => {
  try {
    // 验证邮箱配置
    await verifyEmailConfig()

    // 数据库连接和初始化
    await connectDB()
    await initDB()

    // 路由
    app.use('/api/user', userRoutes)
    app.use('/api/chat', chatRoutes)

    // 错误处理中间件
    app.use((err, req, res, next) => {
      console.error(err.stack)
      res.status(500).json({
        code: 500,
        message: '服务器内部错误',
        success: false
      })
    })

    app.listen(PORT, () => {
      console.log(`服务器运行在端口 ${PORT}`)
    })
  } catch (err) {
    console.error('应用初始化失败:', err)
    process.exit(1)
  }
}

initApp()

module.exports = app
